package com.hongxun.modules.csg.controller;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.hongxun.common.utils.*;
import com.hongxun.common.validator.ValidatorUtils;
import com.hongxun.common.validator.group.AddGroup;
import com.hongxun.common.validator.group.UpdateGroup;
import com.hongxun.modules.api.entity.*;
import com.hongxun.modules.api.service.*;
import com.hongxun.modules.bss.entity.*;
import com.hongxun.modules.bss.service.*;
import com.hongxun.modules.csg.entity.*;
import com.hongxun.modules.csg.entity.dxf.*;

import com.hongxun.modules.csg.entity.dxf.FrmDXFExporter;
import com.hongxun.modules.csg.service.*;
import com.hongxun.modules.csg.tools.DxfUtil;
import com.hongxun.modules.csg.tools.StringUtil;
import com.hongxun.modules.eys.entity.EPBaseEntity;
import com.hongxun.modules.eys.service.EPBaseService;
import com.hongxun.modules.sys.controller.AbstractController;
import com.hongxun.modules.sys.entity.SysDeptEntity;
import com.hongxun.modules.sys.entity.SysRoleEntity;
import com.hongxun.modules.sys.entity.SysUserEntity;
import com.hongxun.modules.sys.service.*;
//import com.lowagie.text.*;
//import com.lowagie.text.Element;
//import com.lowagie.text.Header;
//import com.lowagie.text.pdf.BaseFont;
//import com.lowagie.text.rtf.RtfWriter2;
import com.lowagie.text.*;

import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.rtf.RtfWriter2;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.w3c.dom.*;
//import org.w3c.dom.Text;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;


/**
 * 施工项目表
 *
 * @author zkcn
 * @email youeremail@163.com
 * @date 2018-09-11 11:18:23
 */
@RestController
@RequestMapping("/csg/cpbase")
public class CPBaseController extends AbstractController {
	@Value("${com.hongxun.DXFEROTT}")
	private String DXFEROTT;
	@Autowired
	private CPBaseService cPBaseService;
	@Autowired
	private APBaseService aPBaseService;
	@Autowired
	private SysRoleDeptService sysRoleDeptService;
	@Autowired
	private SysUserRoleService sysUserRoleService;
	@Autowired
	private CScheduleService cScheduleService;
	@Autowired
	private CScheduleReportService cScheduleReportService;
	@Autowired
	private BProjectApplicationService bProjectApplicationService;
	@Autowired
	private BEstimateService bEstimateService;
	@Autowired
	private APOtherService aPOtherService;
	@Autowired
	private APEstimateService aPEstimateService;
	@Autowired
	private BOtherCostService bOtherCostService;
	@Autowired
	private APCostService aPCostService;
	@Autowired
	private EPBaseService ePBaseService;
	@Autowired
	private SysDeptService sysDeptService;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private CArrivalRecordService cArrivalRecordService;
	@Autowired
	private CGoodsDetailService cGoodsDetailService;
	@Autowired
	private DPointService dPointService;
	@Autowired
	private DDrawLineService dDrawLineService;
	@Autowired
	private BMaterialService bMaterialService;
	@Autowired
	private BDataDictionaryService bDataDictionaryService;
	@Autowired
	private BDeviceService bDeviceService;
	@Autowired
	private DCrossCostService dCrossCostService;
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private DDeviceBuyService dDeviceBuyService;
	@Autowired
	private DMaterialBuyService dMaterialBuyService;
	@Autowired
	private APWireService aPWireService;


	/**
	 * 列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("csg:cpbase:list")
	public R list(@RequestParam Map<String, Object> params , String pBType , String pBHive , String pBName , String pBState){
		//查询列表数据
		/*Query query = new Query(params);
		String wheres =" 1=1 ";
		query.put("filterSql",wheres+" ");
		List<CPBaseEntity> cPBaseList = cPBaseService.queryList(query);
		int total = cPBaseService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(cPBaseList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);*/

		Query query = new Query(params);
		String wheres =" 1=1 and  p_b_datastate != '删除' ";
		if(query.get("pBType")!=null&&!query.get("pBType").toString().equals("null") &&!query.get("pBType").toString().equals(""))
		{
			wheres+=" and  p_b_Type = '" + query.get("pBType").toString()+"' ";
		}
//		if(query.get("pBHive")!=null&&!query.get("pBHive").toString().equals("null"))
//		{
//			wheres+=" and  p_b_hive = '" + query.get("pBHive").toString()+"' ";
//		}
		if(query.get("pBState")!=null&&!query.get("pBState").toString().equals("null")&&!query.get("pBState").toString().equals(""))
		{
			wheres+=" and  p_b_state = '" + query.get("pBState").toString()+"' ";
		}
		if(query.get("pBName")!=null&&!query.get("pBName").toString().equals("null"))
		{
			wheres+=" and  p_b_name like '%" + query.get("pBName").toString()+"%' ";
		}
		if(query.get("state")!=null&&query.get("state").toString().equals("isdelno")) {
			wheres += " and  p_b_datastate != '删除' ";
		}
		wheres +=" and ( 1=1  ";
		boolean myprio=false;
		if(query.get("ourid")!=null&&query.get("ourid").toString().equals("isok")) {
			List<Long> roleIdList = sysUserRoleService.queryRoleIdList(getUserId());
			String deptId = "";

			for (Long id : roleIdList) {
				SysRoleEntity sysRoleEntity = sysRoleService.queryObject(id);
				if(sysRoleEntity.getRemark().equals("是"))
				{
					myprio=true;
				}
				List<Long> deptIdList = sysRoleDeptService.queryDeptIdList(id);
				for (Long sid : deptIdList) {
					deptId += sid + ",";
				}
			}
			if(deptId.length()>0)
			{
				deptId =deptId.substring(0,deptId.length()-1);
				wheres += " and  p_b_orgid in ("+deptId+")";
			}
			else
			{
				wheres += " and  p_b_orgid in ( -1 )";
			}



		}

//			SysUserEntity sysus =  sysUserService.queryObject(getUserId());
//			SysDeptEntity sysde = sysDeptService.queryObject(sysus.getDeptId());
//			if (sysde.getParentId() == 17) {
//				myprio = true;
//			}

		if(!myprio)
		{
			wheres += "and  FIND_IN_SET('" + getUserId() + "',p_b_collectid) or  FIND_IN_SET('" + getUserId() + "',p_b_reckonid)";

		}/*else{
			wheres += "and  FIND_IN_SET('" + getUserId() + "',p_b_reckonid)";
		}*/
		wheres +=" )";


		query.put("filterSql",wheres+" ");
		List<CPBaseEntity> aPBaseList = cPBaseService.queryList(query);
		int total = cPBaseService.queryTotal(query);

		PageUtils pageUtil = new PageUtils(aPBaseList, total, query.getLimit(), query.getPage());

		return R.ok().put("page", pageUtil);

	}


	@RequestMapping("/select")
	public R select(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		String wheres =" 1=1 ";
		wheres += " and  p_b_datastate != '删除' ";


		if(query.get("ourid")!=null&&query.get("ourid").toString().equals("isok")) {
			List<Long> roleIdList = sysUserRoleService.queryRoleIdList(getUserId());
			String deptId = "";

			for (Long id : roleIdList) {
				List<Long> deptIdList = sysRoleDeptService.queryDeptIdList(id);
				for (Long sid : deptIdList) {
					deptId += sid + ",";
				}
			}
			if(deptId.length()>0)
			{
				deptId =deptId.substring(0,deptId.length()-1);
				wheres += " and  p_b_orgid in ("+deptId+")";
			}
			else
			{
				wheres += " and  p_b_orgid in ( -1 )";
			}

		}
		if(query.get("pname")!=null&& !query.get("pname").toString().equals("")){
			wheres+=" and  p_b_name = '" + query.get("pname").toString()+"' ";
		}

		query.put("filterSql",wheres+" ");
		List<CPBaseEntity> cPBaseList = cPBaseService.queryList(query);

		return R.ok().put("returnlist", cPBaseList);
	}



	@RequestMapping("/mapselect")
	public R mapselect(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		String wheres =" 1=1 ";
		wheres += " and  p_b_datastate != '删除' ";
		wheres += " and  p_b_state != '30' ";

		if(query.get("ourid")!=null&&query.get("ourid").toString().equals("isok")) {
			List<Long> roleIdList = sysUserRoleService.queryRoleIdList(getUserId());
			String deptId = "";

			for (Long id : roleIdList) {
				List<Long> deptIdList = sysRoleDeptService.queryDeptIdList(id);
				for (Long sid : deptIdList) {
					deptId += sid + ",";
				}
			}
			if(deptId.length()>0)
			{
				deptId =deptId.substring(0,deptId.length()-1);
				wheres += " and  p_b_orgid in ("+deptId+")";
			}
			else
			{
				wheres += " and  p_b_orgid in ( -1 )";
			}

		}

		query.put("filterSql",wheres+" ");
		List<CPBaseEntity> cPBaseList = cPBaseService.queryList(query);

		return R.ok().put("returnlist", cPBaseList);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/info/{guid}")
	@RequiresPermissions("csg:cpbase:info")
	public R info(@PathVariable("guid") String guid){
		CPBaseEntity cPBase = cPBaseService.queryObject(guid);

		return R.ok().put("cPBase", cPBase);
	}

	/**
	 * 保存
	 */
	/*@RequestMapping("/save")
	@RequiresPermissions("csg:cpbase:save")
	public R save(@RequestBody CPBaseEntity cPBase){
		cPBaseService.save(cPBase);

		return R.ok();
	}*/



	/**
	 *  保存
	 *
	 * @param
	 * @return
	 */
	@RequestMapping("/save")
	@RequiresPermissions("csg:cpbase:save")
	public R save(@RequestBody CPBaseEntity cPBase){
		ValidatorUtils.validateEntity(cPBase, AddGroup.class);
		cPBase.setPBDatastate("新增");
		cPBase.setPBAddtime(new Date());
		cPBase.setPBHive("10");
		Map<String ,Object > maps= new HashMap<String ,Object>();

		String wheres =" 1=1 ";
		if(cPBase.getPBType()!=null&&!cPBase.getPBType().equals(""))
		{
			wheres+=" and  p_a_type like '%" + cPBase.getPBType()+"%' ";
		}
		else
		{
			return R.error("请选择项目类型");
		}
		maps.put("filterSql",wheres+" ");
		List<BProjectApplicationEntity> bProjectApplicationList = bProjectApplicationService.queryList(maps);
		List<BEstimateEntity> bEstimateListall =  new ArrayList<BEstimateEntity>();

		if(bProjectApplicationList.size()>0)
		{
			cPBase.setAGuid(bProjectApplicationList.get(0).getGuid());
			Map<String ,Object > mapss= new HashMap<String ,Object>();
			String wheress =" 1=1 ";
			wheress+=" and  a_guid = '" + bProjectApplicationList.get(0).getGuid()+"' ";
			wheress+=" and  e_type = '" + cPBase.getPBType()+"' ";
			mapss.put("filterSql",wheress+" ");
			List<BEstimateEntity> bEstimateList = bEstimateService.queryList(mapss);


			if(bEstimateList.size()>0)
			{

				String SGuid ="";
				for(BEstimateEntity bestimateEntity :bEstimateList) {
					bEstimateListall.add(bestimateEntity);
					if (!SGuid.contains(bestimateEntity.getBGuid())) {
						SGuid += bestimateEntity.getBGuid() + ",";
					}

				}
				SGuid=SGuid.substring(0,SGuid.length()-1);
				cPBase.setSGuid(SGuid);
			}
			else
			{
				return R.error("所选项目类型没有估算简表，请先配置估算简表");
			}

		}
		else
		{
			return R.error("所选项目类型没有申请书，请先配置申请书");
		}
		if (cPBase.getPBLongitude() != null && !cPBase.getPBLongitude().equals("null")) {

//			SysDeptEntity s1 = sysDeptService.queryObject(Long.parseLong(cPBase.getPArentid()));
//			SysDeptEntity s2 = sysDeptService.queryObject(Long.parseLong(cPBase.getPArentname()));
			cPBase.setPBLongitude(cPBase.getPBLongitude());
			cPBase.setPBLatitude(cPBase.getPBLatitude());

//			cPBase.setPBLongitude(BigDecimal.valueOf(Long.parseLong(cPBase.getPBLongitude())));
//			cPBase.setPBLatitude(BigDecimal.valueOf(Long.parseLong(cPBase.getPBLatitude())));

		}
		cPBase.setPBCollectid(cPBase.getPBCollectid().replace("\"","").replace("[","").replace("]",""));
		cPBase.setPBReckonid(cPBase.getPBReckonid().replace("\"","").replace("[","").replace("]",""));

		cPBase.setPBOrgid(getDeptId());
		cPBaseService.save(cPBase);
		//保存其他信息
		APOtherEntity aPOtherEntity = new  APOtherEntity();
		aPOtherEntity.setPGuid(cPBase.getGuid());
		aPOtherEntity.setPODatastate("新增");
		aPOtherService.save(aPOtherEntity);
		//保存估算简表
		for(BEstimateEntity bestimateEntity:bEstimateListall) {
			APEstimateEntity APEstimateEntity = new APEstimateEntity();
			APEstimateEntity.setPGuid(cPBase.getGuid());
			APEstimateEntity.setPBGuid(bestimateEntity.getBGuid());
			APEstimateEntity.setPEDatastate("新增");
			APEstimateEntity.setPEItem(bestimateEntity.getEItem());
			APEstimateEntity.setPEName(bestimateEntity.getEName());
			APEstimateEntity.setPESysRatio(bestimateEntity.getESysRatio());
			APEstimateEntity.setPEOwnRatio(bestimateEntity.getEOwnRatio());
			APEstimateEntity.setPEInitial(BigDecimal.ZERO);
			APEstimateEntity.setPEFinal(BigDecimal.ZERO);
			aPEstimateService.save(APEstimateEntity);
		}
		//其他费用表
		Map<String ,Object > mapss= new HashMap<String ,Object>();

		String wheress =" 1=1 ";
		wheress+=" and  a_guid = '" + cPBase.getAGuid()+"' ";
		mapss.put("filterSql",wheress+" ");
		List<BOtherCostEntity> bOtherCostList = bOtherCostService.queryList(mapss);
		for(BOtherCostEntity BOtherCostEntity:bOtherCostList)
		{
			APCostEntity aPCostEntity = new APCostEntity();
			aPCostEntity.setPCDatastate("新增");
			aPCostEntity.setPGuid(cPBase.getGuid());
			aPCostEntity.setPCNum(BOtherCostEntity.getOCNum());
			aPCostEntity.setPCDetail(BOtherCostEntity.getOCDetail());
			aPCostEntity.setPCExplain(BOtherCostEntity.getOCExplain());
			aPCostEntity.setPCSort(BOtherCostEntity.getOCSort());
			aPCostEntity.setPCToll(BOtherCostEntity.getOCToll());
			aPCostEntity.setPCPrice(BigDecimal.ZERO);
			aPCostService.save(aPCostEntity);
		}


		return R.ok();
	}




	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("csg:cpbase:update")
	public R update(@RequestBody CPBaseEntity cPBase){
		ValidatorUtils.validateEntity(cPBase, UpdateGroup.class);
		cPBase.setPBCollectid(cPBase.getPBCollectid().replace("\"","").replace("[","").replace("]",""));
		cPBase.setPBReckonid(cPBase.getPBReckonid().replace("\"","").replace("[","").replace("]",""));

		cPBaseService.update(cPBase);

		return R.ok();
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("csg:cpbase:delete")
	public R delete(@RequestBody String[] guids){

//		cPBaseService.deleteBatch(guids);

		cPBaseService.logical_delete(guids);

		return R.ok();
	}


	/**
	 * 单个项目已选施工参与人查看
	 */
	@RequestMapping("/selectIndividual")
	public R selectIndividual(@RequestParam Map<String, Object> params){

		String pGuid = params.get("pGuid").toString();
		String where = " 1=1 and guid = '"+pGuid+"'";
		Map<String , Object > map = new HashMap<>();
		map.put("filterSql",where);
		List<SysUserEntity> sysUserEntityList = new ArrayList<>();
		List<CPBaseEntity> cpBaseEntityList = cPBaseService.queryList(map);
		for (CPBaseEntity cpBaseEntity : cpBaseEntityList) {
			String s1 = cpBaseEntity.getPBReckonid();
			if (s1 != null && !s1.equals("")) {
				String s2 = s1.substring(0,s1.length());

				if (s2 != null && !s2.equals("")) {
					for (String idString : s2.split(",")) {
						SysUserEntity sysUserEntity = sysUserService.queryObject(Long.parseLong(idString));
						sysUserEntityList.add(sysUserEntity);
					}
				}
			}
		}



		return R.ok().put("returnlist", sysUserEntityList);
	}


	/**
	 * 	加载list时，显示所有项目的施工参与人
	 *
	 * @param params
	 * @return
	 */
	@RequestMapping("/selectShiGong")
	public R selectShiGong(@RequestParam Map<String, Object> params){

		Query query = new Query(params);
		String wheres =" 1=1 ";
		query.put("filterSql",wheres+" ");
		List<CPBaseEntity> cPBaseList = cPBaseService.queryList(query);
		List<SysUserEntity> sysUserEntityList = new ArrayList<>();
		List list = new ArrayList<>();

		//  2018/10/11  获取所有项目已选施工参与人员ID
		for (CPBaseEntity cpBaseEntity : cPBaseList) {
			if (cpBaseEntity.getPBReckonid() != null && !cpBaseEntity.getPBReckonid().equals("")) {
				String s2 = cpBaseEntity.getPBReckonid().substring(0,cpBaseEntity.getPBReckonid().length());
				if (s2 != null && !s2.equals("")) {
					for (String idString : s2.split(",")) {
						list.add(idString);
					}
				}
			}
		}

		// 2018/10/11  list去重
		removeDuplicate(list);

		// 2018-10-11  施工人员
		for (Object o : list) {
			SysUserEntity sysUserEntity = sysUserService.queryObject(Long.parseLong(o.toString()));
			sysUserEntityList.add(sysUserEntity);
		}

		return R.ok().put("returnlist", sysUserEntityList);
	}


	/**
	 *  list 去重
	 *
	 * @param list
	 * @return
	 */
	private static List<String> removeDuplicate(List<String> list) {
		LinkedHashSet<String> set = new LinkedHashSet<String>(list.size());
		set.addAll(list);
		list.clear();
		list.addAll(set);
		return list;
	}


	/**
	 *  施工项目归档
	 *
	 * @param guid
	 * @return
	 */
	@RequestMapping("/archives")
	public R upbasegd( @RequestBody String guid){
		CPBaseEntity cpBaseEntity = cPBaseService.queryObject(guid);
		cpBaseEntity.setPBState("30");
		cPBaseService.update(cpBaseEntity);
		return R.ok();
	}


	/**
	 * 进入验收阶段
	 *
	 * @param guid
	 * @return
	 */
	@RequestMapping("/gotosg")
	public R gotosg(@RequestBody String guid){
		CPBaseEntity cPBase = cPBaseService.queryObject(guid);
		if(!cPBase.getPBState().equals("30"))
		{
			return R.error("项目没有在归档阶段，请先归档在进入施工阶段");
		}
		EPBaseEntity ePBase = ePBaseService.queryObject(guid);
		if(ePBase!=null)
		{
			return R.error("项目在施工阶段已经存在，请在施工阶段进行查看");
		}
		ePBase = new EPBaseEntity();
		try {
			BeanUtils.copyProperties(ePBase, cPBase);
			ePBaseService.save(ePBase);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return R.ok();
	}



	/**
	 * 归档
	 *
	 * @param guid
	 * @return
	 */
	@RequestMapping("/guidang")
	public R guidang(@RequestBody String guid){
		CPBaseEntity cPBase = cPBaseService.queryObject(guid);
		if(!cPBase.getPBState().equals("30"))
		{
			return R.error("项目没有在归档阶段，请先归档在进入施工阶段");
		}
		EPBaseEntity ePBase = ePBaseService.queryObject(guid);
		if(ePBase!=null)
		{
			return R.error("项目在施工阶段已经存在，请在施工阶段进行查看");
		}
		ePBase = new EPBaseEntity();
		try {
			BeanUtils.copyProperties(ePBase, cPBase);
			ePBaseService.save(ePBase);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return R.ok();
	}



	/**
	 * 	施工队
	 * @param params
	 * @return
	 */
	@RequestMapping("/selectDepartment")
	public R selectDepartment(@RequestParam Map<String, Object> params){
		//查询列表数据

		Long construction_Id = 17L;//施工单位ID

		SysDeptEntity sysDeptEntity = new SysDeptEntity();
		List<SysDeptEntity> deptList = new ArrayList<>();
		String s1 = sysDeptService.getSubDeptIdList(construction_Id);
		int end = s1.lastIndexOf(",");
		s1 = s1.substring(0,end);
		for (String deptId:s1.split(",")) {
			if (!deptId.equals("17")) {
				sysDeptEntity = sysDeptService.queryObject(Long.parseLong(deptId));
			}
			deptList.add(sysDeptEntity);
		}


		return R.ok().put("returnlist", deptList);
	}



	/**
	 * 施工队下辖人员
	 * @param params
	 * @return
	 */
	@RequestMapping("/selectToDeptid")
	public R selectToDeptid(@RequestParam Map<String, Object> params){
		//查询列表数据
		List<SysUserEntity> userList = new ArrayList<>();
		Map<String , Object> map = new HashMap<>();
		String where = " 1=1 ";
		if (params.get("id") != null && !params.get("id").toString().equals("")) {

			Long deptId = Long.parseLong(params.get("id").toString());

			userList = sysUserService.queryListBydeptid(deptId);



//			where += " and dept_id="+deptId;
//			map.put("filterSql",where);
//			userList = sysUserService.queryList(map);
		}

		return R.ok().put("returnlist", userList);
	}


	/**
	 * 获取所有点位信息
	 * @param pGuid		项目ID
	 * @param LineArea	线路台区
	 * @return
	 * @addTime 2018-10-17 11:31:54
	 */
//	@RequestMapping("getAllPointInfo")
	public List getAllPointInfo(String pGuid , String LineArea){

	// TODO: 2018/11/23  p_r_guid 所属项目范围ID ，就是台区ID，需要点位表d_point联合项目范围表a_p_range
	// 点位表中的p_r_guid和交叉跨越表中的p_r_guid都是所属项目范围ID（线路台区ID），和项目范围表a_p_range进行关联

		//组装数据
		List list = new ArrayList();
		List<DPointEntity> pointList = new ArrayList<>();
		List<DDrawLineEntity> laxList = new ArrayList<>();
		List<DDrawLineEntity> laxianList = new ArrayList<>();
		List<DCrossCostEntity> dCrossList = new ArrayList<>();
		List<DCrossCostEntity> dCrossCostList = new ArrayList<>();
		Map<String , Object> pointMap = new HashMap<>();
//		String pGuid = params.get("pGuid").toString();//项目ID

		//1.根据项目ID获取点位信息
		String pointWhere = " 1=1 and p_guid='"+pGuid+"' and p_p_worktype='新增' and p_p_datastate != '删除' ";
		//台区选择
		if(LineArea != null && !LineArea.equals("")){
			pointWhere += " and p_r_guid='"+LineArea+"'";
		}
		pointMap.put("filterSql", pointWhere);
		pointList = dPointService.queryList(pointMap);


		//2.根据点位获取拉线信息
		for (DPointEntity dPointEntity : pointList) {

			//杆塔拉线
			pointMap.clear();
			if(dPointEntity.getPPName().equals("杆塔") && dPointEntity.getPPWirenum()>=1) {
				String laxianWhere = " 1=1 and p_guid='" + pGuid + "' and p_p_guid='" + dPointEntity.getGuid() + "' and d_l_datastate !='删除' ";
				pointMap.put("filterSql", laxianWhere);
				laxList = dDrawLineService.queryList(pointMap);
				laxianList.addAll(laxList);
			}

			//交叉跨越
			pointMap.clear();
			String crossCostWhere = " 1=1 and c_c_upguid='"+dPointEntity.getGuid()+"' and c_c_datastate !='删除'";
			//台区选择
			if(LineArea != null && !LineArea.equals("")){
				crossCostWhere += " and p_r_guid='"+LineArea+"'";
			}
			pointMap.put("filterSql", crossCostWhere);
			dCrossList = dCrossCostService.queryList(pointMap);
			dCrossCostList.addAll(dCrossList);

		}

		//信息描述
		String pointInfo = getProInfoOnCad(pGuid,LineArea);

		//项目名称
		APBaseEntity apBaseEntity = aPBaseService.queryObject(pGuid);
		String projectName = apBaseEntity.getPBName();

		//设计单位
		SysDeptEntity sysDeptEntity = sysDeptService.queryObject(apBaseEntity.getPBOrgid());
		String complanName = sysDeptEntity.getName();

		//组码数据传递
//		return R.ok().put("pointList",JSON.toJSONString(pointList))
//				.put("laxianList",JSON.toJSONString(laxianList))
//				.put("crossCostList",JSON.toJSONString(dCrossCostList))
//				.put("textgcmc",projectName)
//				.put("textsjdw",complanName)
//				.put("projectName",projectName)
//				.put("pointInfo",pointInfo);

		// 模板数据传递

		list.add(pointList);
		list.add(laxianList);
		list.add(dCrossCostList);
		list.add(projectName);
		list.add(complanName);
		list.add(projectName);
		list.add(pointInfo);

		return list;
//		return R.ok().put("pointList",pointList)
//				.put("laxianList",laxianList)
//				.put("crossCostList",dCrossCostList)
//				.put("textgcmc",projectName)
//				.put("textsjdw",complanName)
//				.put("projectName",projectName)
//				.put("pointInfo",pointInfo);
	}

	/**
	 * 	list去重
	 *
	 * @param list
	 * @return
	 */
//	public static List removeDuplicate(List list) {
//		HashSet h = new HashSet(list);
//		list.clear();
//		list.addAll(h);
//		return list;
//	}


	/**
	 * 项目信息组装
	 *
	 * @param pGuid
	 * @return
	 * @Time 2018-11-15 16:55:01 修改
	 */
	public String getProInfoOnCad(String pGuid , String LineArea){

		StringBuffer sBuff = new StringBuffer();
		List<DPointEntity> list_DPoint_10kv = null;
		List<DPointEntity> list_DPoint_all = null;
		List<APBaseEntity> list_APBase_10kv = null;
		List<BMaterialEntity> list_BMater = null;

		Map<String , Object> c_10kv_Map = new HashMap<>();
		Map<String , Object> c_all_Map = new HashMap<>();
		DecimalFormat df = new DecimalFormat("######0.000");

		//所有线路
		String c_all = " 1=1 and p_guid='"+pGuid+"' and p_p_worktype='新增' ";
		//台区
		if(LineArea != null  && !LineArea.equals("")){
			c_all += " and p_r_guid='"+LineArea+"'";
		}
		c_all_Map.put("filterSql",c_all);
		list_DPoint_all = dPointService.queryList(c_all_Map);


		/*  10kv线路导线长度、材料及类型 */
		String c_10kv = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '1' and p_p_worktype='新增' ";
		//台区
		if(LineArea != null && !LineArea.equals("")){
			c_10kv += " and p_r_guid='"+LineArea+"'";
		}
		c_10kv_Map.put("filterSql",c_10kv);
		list_DPoint_10kv = dPointService.queryList(c_10kv_Map);

		String info_10kv = "";
		String where_10kv = " 1=1 ";
		Map<String , Object> map_10kv = new HashMap<>();
		double total_line_length = 0;	//线路总长度
		double line_length_10kv = 0;	//10kv线路长度
		double sum_10kv = 0;

		if (list_DPoint_10kv != null) {
			List<String> list11 = new ArrayList<>();
			for (int i = 0; i < list_DPoint_10kv.size(); i++) {
				// 计算线路长度
				DPointEntity dPointEntity = list_DPoint_10kv.get(i);
				if (dPointEntity.getPPAutospan() == null || dPointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0的情况，
					line_length_10kv = 0;
				}else{//档距不为空且不为0时
					double span = Double.parseDouble(dPointEntity.getPPAutospan().toString());
					total_line_length += span;
					line_length_10kv += span;
					sum_10kv += span;
				}
				//选出导线材料ID
				if(dPointEntity.getPWGuid() != null){
					list11.add(dPointEntity.getPWGuid());
				}

			}
			// 导线材料及类型
			List<String > list_10 = removeDuplicate(list11);
			for (String s : list_10) {
				where_10kv += " and p_m_guid='"+s+"'";
				map_10kv.put("filterSql",where_10kv);
				List<APWireEntity> bm = aPWireService.queryList(map_10kv);
				for (APWireEntity dMater : bm) {
					info_10kv += dMater.getPWName() + "线型" + df.format(sum_10kv / 1000) + "km";
					break;
				}
				info_10kv += "、";
			}
		}
		info_10kv = removeDunhao(info_10kv);
		info_10kv = info_10kv.substring(info_10kv.indexOf("，")+1,info_10kv.length());



		/*  0.38kv线路导线长度、材料及类型 *********/
		List<DPointEntity> list_DPoint_380v = null;
		List<APBaseEntity> list_APBase_380v = null;
		List<BMaterialEntity> list_BMater_380v = null;
		Map<String , Object> c_380v_Map = new HashMap<>();
		String c_380v = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '2' and p_p_worktype='新增' ";
		//台区
		if(LineArea != null && !LineArea.equals("")){
			c_380v += " and p_r_guid='"+LineArea+"'";
		}
		c_380v_Map.put("filterSql",c_380v);
		list_DPoint_380v = dPointService.queryList(c_380v_Map);

		String info_380v = "";
		String where_380v = " 1=1 ";
		Map<String , Object> map_380v = new HashMap<>();
		double line_length_380v = 0;	//380v线路长度
		double sum_380v = 0;
		if (list_DPoint_380v != null) {
			List<String> list22 = new ArrayList<>();
			for (DPointEntity dPointEntity : list_DPoint_380v) {
				// 计算长度
				if(dPointEntity.getPPAutospan() ==null || dPointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0时
					line_length_380v = 0;
				}else{//档距不为空且不为0时
					double span = Double.parseDouble(dPointEntity.getPPAutospan().toString());
					total_line_length += span;
					line_length_380v += span;
					sum_380v += span;
				}
				//导线材料ID
				if(dPointEntity.getPWGuid() != null){
					list22.add(dPointEntity.getPWGuid());
				}
			}
			// 导线材料及型号
			List<String> list_380 = removeDuplicate(list22);
			for (String s : list_380) {
				where_380v += " and p_m_guid='"+s+"'";
				map_380v.put("filterSql",where_380v);
				List<APWireEntity> bm = aPWireService.queryList(map_380v);

				for (APWireEntity dMater : bm) {
					info_380v += dMater.getPWName()+ "线型" +df.format(sum_380v / 1000)+ "km";
					break;
				}
				info_380v += "、";
			}

		}
		info_380v = removeDunhao(info_380v);
		info_380v = info_380v.substring(info_380v.indexOf("，")+1,info_380v.length());



		/*  0.22kv线路导线长度、材料及类型 *********/
		List<DPointEntity> list_DPoint_220v = null;
		List<APBaseEntity> list_APBase_220v = null;
		List<BMaterialEntity> list_BMater_220v = null;
		Map<String , Object> c_220v_Map = new HashMap<>();
		String c_220v = " 1=1 and p_guid='"+pGuid+"' and p_p_voltage= '3' and p_p_worktype='新增' ";
		//台区
		if(LineArea != null && !LineArea.equals("")){
			c_220v += " and p_r_guid='"+LineArea+"'";
		}
		c_220v_Map.put("filterSql",c_220v);
		list_DPoint_220v = dPointService.queryList(c_220v_Map);

		String info_220v = "";
		String where_220v = " 1=1 ";
		Map<String , Object> map_220v = new HashMap<>();
		double line_length_220v = 0;	//10kv线路长度
		double sum_220v = 0;
		if (list_DPoint_220v != null) {
			List<String> list33 = new ArrayList<>();
			for (DPointEntity dPointEntity : list_DPoint_220v) {
				//导线长度
				if(dPointEntity.getPPAutospan() == null || dPointEntity.getPPAutospan().toString().equals("0.00")){//档距为空或者为0时
					line_length_220v = 0;
				}else{//档距不为空且不为0时
					double span = Double.parseDouble(dPointEntity.getPPAutospan().toString());
					total_line_length += span;
					line_length_220v += span;
					sum_220v += span;
				}
				//导线材料ID
				if(dPointEntity.getPWGuid() != null){
					list33.add(dPointEntity.getPWGuid());
				}
			}
			//导线材料及类型
			List<String> list_220 = removeDuplicate(list33);
			for (String s : list_220) {
				where_220v += " and p_m_guid='"+s+"'";
				map_220v.put("filterSql",where_220v);
				List<APWireEntity> bm = aPWireService.queryList(map_220v);

				for (APWireEntity dMater : bm) {
					info_220v += dMater.getPWName() + "线型" + df.format(sum_220v / 1000) + "km";
					break;
				}
				info_220v += "、";
			}
		}
		info_220v = removeDunhao(info_220v);
		info_220v = info_220v.substring(info_220v.indexOf("，")+1,info_220v.length());



		/*    信息组装 ******/
		if (total_line_length == 0) {
			sBuff.append("1、本工程线路总长" + df.format(total_line_length / 1000) + "km。");
		} else {
			sBuff.append("1、本工程线路总长" + df.format(total_line_length / 1000) + "km，其中");
			if (info_10kv!=null && !info_10kv.equals("")) {
				sBuff.append("10kV线路" + df.format(sum_10kv / 1000) + "km，" + info_10kv);
				if ((info_380v!=null && !info_380v.equals("")) || (info_220v!=null && !info_220v.equals(""))) {
					sBuff.append("；");
				}
			}
			if (info_380v!=null && !info_380v.equals("")) {
				sBuff.append("0.4kV线路" + df.format(sum_380v / 1000) + "km，" + info_380v);
				if (info_220v!=null && !info_220v.equals("")) {
					sBuff.append("；");
				}
			}
			if (info_220v!=null && !info_220v.equals("")) {
				sBuff.append("0.22kV线路" + df.format(sum_220v / 1000) + "km，" + info_220v);
			}
			sBuff.append("。");
		}


		//杆塔
		List<BDataDictionaryEntity> bdlist = new ArrayList<>();
		Map<String ,Object> bdMap = new HashMap<>();
		String str = "";
		String s1 = "";
		int poleTotal = 0;
		int alld_point = 0;
		String where_pole = " 1=1 ";
		Map<String , Object> map_pole = new HashMap<>();
		List<String> list44 = new ArrayList<>();
		if (list_DPoint_all != null) {
			for (DPointEntity dPointEntity : list_DPoint_all) {
				if(dPointEntity.getPPName().equals("杆塔")) {
					// 计算杆塔基数
					poleTotal += 1;
					// 获取杆高
					list44.add(dPointEntity.getPPBar().toString());
				}
			}
			// 获取杆高及基数(去重)
			List<String> list_pole = removeDuplicate(list44);
			for (String s : list_pole) {
				where_pole = " and p_p_worktype = '新增' AND p_p_datastate != '删除' and p_p_name='杆塔' and p_p_bar='"+s+"' and p_guid='"+pGuid+"'";
				//台区
				if(LineArea != null && !LineArea.equals("")){
					where_pole += " and p_r_guid='"+LineArea+"'";
				}
				map_pole.put("filterSql",where_pole);
				Integer pole_pbar = dPointService.queryTotal(map_pole);
				s = s.substring(0,s.indexOf("."));
				str = s+"米"+pole_pbar+"基"+"、"+str;
			}
		}
		str = removeDunhao(str);//去除末尾顿号
		if (poleTotal == 0) {
			sBuff.append("2、本工程杆塔" + poleTotal + "基。");
		} else {
			sBuff.append("2、本工程杆塔" + poleTotal + "基，" + str + "；");
		}


		//变压器
		List<BDataDictionaryEntity> bylist = new ArrayList<>();
		Map<String ,Object> byMap = new HashMap<>();
		String str22 = "";
		int transTotal = 0;
		int alld_point1 = 0;
		String where_T = " 1=1 ";
		Map<String , Object> map_T = new HashMap<>();
		List<String> list55 = new ArrayList<>();
		boolean tr = false ;
		if (list_DPoint_all != null) {
			for (DPointEntity dPointEntity : list_DPoint_all) {
				if(dPointEntity.getPPName().equals("柱上变压器")) {
//					alld_point1 +=1;
					// 获取点位ID
					list55.add(dPointEntity.getGuid());
					tr = true;
				}
			}
			if(tr) {
				List<String> list_Tt = removeDuplicate(list55);//去重
				List<String> list_dev = new ArrayList<>();
				for (String s : list_Tt) {
					// 点位设备表查询
					where_T = " and p_p_guid='" + s + "' and d_b_bigtype='变压器' and d_b_datastate !='删除' ";
					map_T.put("filterSql", where_T);
					List<DDeviceBuyEntity> DDeviceList = dDeviceBuyService.queryList(map_T);
					for (DDeviceBuyEntity dDev : DDeviceList) {
						list_dev.add(dDev.getDLabel());
					}
				}
				//变压器型号及数量
				List<String> list_ss = removeDuplicate(list_dev);//去重
				String where_Num = " 1=1 ";
				Map<String, Object> map_Num = new HashMap<>();
				for (String s2 : list_ss) {
					where_Num = " and d_label='" + s2 + "' and p_guid='" + pGuid + "' AND d_b_bigtype='变压器' AND d_label ='" + s2 + "'";
					map_Num.put("filterSql", where_Num);
					int _Num = dDeviceBuyService.queryTotal(map_Num);
					alld_point1 = _Num;
					str22 += s2 + "型变压器" + alld_point1 + "台" + "、" + str22;
				}

				str22 = removeDunhao(str22);
				if(!str22.equals("")) {
					if(str22.lastIndexOf("、") != -1) {
						str22 = str22.substring(0, str22.lastIndexOf("、"));
						sBuff.append(str22 + "。");
					}else{
						sBuff.append(str22 + "。");
					}
				}
			}
		}else {
			sBuff.append("设备类别-设备容量变压器0台。");
		}


		//交叉跨越
		List<DCrossCostEntity> list_dcross = new ArrayList<>();
		Map<String , Object> crossMap = new HashMap<>();
		String crossWhere = " 1=1 and p_guid='"+pGuid+"' and c_c_datastate != '删除' ";
		//台区
		if(LineArea != null && !LineArea.equals("")){
			crossWhere += " and p_r_guid='"+LineArea+"'";
		}
		crossMap.put("filterSql",crossWhere);
		list_dcross = dCrossCostService.queryList(crossMap);

		if (list_dcross.size()>0) {
			sBuff.append("3、交叉跨越：");
			crossMap.clear();
			int aa = 0 ;
			for (DCrossCostEntity listDcross : list_dcross) {

				String cross_1 = " 1=1 and p_guid='"+pGuid+"' and c_c_name='"+listDcross.getCCName()+"' and c_c_datastate != '删除' ";
				//台区
				if(LineArea != null && !LineArea.equals("")){
					cross_1 += " and p_r_guid='"+LineArea+"'";
				}
				crossMap.put("filterSql",cross_1);
				aa = dCrossCostService.queryTotal(crossMap);
				sBuff.append(listDcross.getCCName() + "" + aa + "处");
			}
			sBuff.append("。");
		}else {
			sBuff.append("3、交叉跨越0处。");
		}


		System.err.println("项目信息："+sBuff.toString());



		return sBuff.toString();
	}



	/**
	 * 去掉末尾顿号
	 * @param str
	 * @return
	 */
	public String removeDunhao(String str){
		if(str!=null && !str.equals("")){
			if(str.lastIndexOf("、") == str.length()-1){
				str = str.substring(0,str.length()-1);
			}
		}
		return str;
	}


	/**
	 * 	导出DXF文件(旧版导出--中文乱码以解决--2019年7月26日15:42:13)   大修技改app接口
	 *
	 * @param params
	 * @Time 2018-10-14 10:07:22
	 */
	@RequestMapping("/exportDXF")
	public void exportDXF(@RequestParam Map<String , Object> params ,
						  HttpServletRequest request ,
						  HttpServletResponse response) throws Exception {

		response.setCharacterEncoding("UTF-8");

		String guid = params.get("guid").toString();
		APBaseEntity apBaseEntity = aPBaseService.queryObject(guid);
		String fName = apBaseEntity.getPBName();

//		Map<String , Object> map = getAllPointInfo(params.get("pGuid").toString(),null);
		List list = getAllPointInfo(guid,null);
		//开始作图(调用数据，传递给swing)
//		FrmDXFExporter frame = new FrmDXFExporter(map);					//	map	 传值
		NewDXFExporter frame = new NewDXFExporter(list , DXFEROTT);	//	list 传值
//		frame.jbtnSave_actionPerformed(map);
		frame.jbtnSave_actionPerformed(list);	//	dxf保存文件

		String newPath = DXFEROTT+"foundation";	//	路径
		File dir = new File(newPath);
		if (!dir.exists()) {
			dir.mkdirs();		// 	mkdirs创建多级目录
		}
		//	创建文件
		File checkFile = new File(newPath + "/"+fName+".dxf");
		if (!checkFile.exists()) {
			checkFile.createNewFile();// 创建目标文件
		}
		String pathOne = newPath + "/"+fName+".dxf";
		response.reset();         //清除空格等操作
		//1.设置文件ContentType类型
		response.setContentType("application/x-dxf;charset=utf-8");//文档
		//2.设置文件头
		String name = URLEncoder.encode(fName+"-" + System.currentTimeMillis(),"UTF-8");
		response.setHeader("Content-Disposition", "attachment;fileName="+name+".dxf");

		ServletOutputStream out;
		File file = new File(pathOne);
		try {
			FileInputStream inputStream = new FileInputStream(file);
			//3.通过response获取ServletOutputStream对象(out)
			out = response.getOutputStream();
			int b = 0;
			byte[] buffer = new byte[512];
			while (b != -1){
				b = inputStream.read(buffer);
				//4.写到输出流(out)中
				out.write(buffer,0,b);
			}
			inputStream.close();
			out.close();
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	/**
	 *  导出DXF文件(新版--以模板进行导出)
     *
	 * @param request
	 * @param response
	 * DXF导出需要改到项目储备和施工中去
	 */
	@RequestMapping(value = "/expDxfFile")
	public void expDxfFile(HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		try {
			String template = "dxf2007_test.ftl";	//模板名称
			String namss=request.getParameter("svgStr").replace("@#@","<")
					.replace("$#$",">");//对HTML标签进行反转义

			// 生成DXF文件所需组码
			Map<String, Object> result = DxfUtil.svgToDxfData(namss);
			String fileOnlyName = System.currentTimeMillis() + ".dxf";

			String dxf_file_name = request.getParameter("dxf_file_name");//文件名
			if (StringUtil.isNotEmpty(dxf_file_name)) {
				fileOnlyName = dxf_file_name + ".dxf";
			}
			// 存放路径
			String filePath = "D:\\budgetDXF\\foundation";
			//生成Excel
			String url = WordUtil.createWord(result, template, filePath, fileOnlyName);
			if (StringUtil.isNotEmpty(url)) {
				File file = new File(url);
				//得到文件名
				String filename = file.getName();
				//如果文件不存在会抛出FileNotFoundException异常，需要捕获后进行处理
				InputStream fis = new BufferedInputStream(new FileInputStream(url));
				byte[] buffer = new byte[fis.available()];
				fis.read(buffer);
				fis.close();
				//清空response
				response.reset();
				String downLoadName = new String(filename.getBytes("gbk"), "iso8859-1");
				// 设置response的Header
				response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);
				response.addHeader("Content-Length", "" + file.length());
				OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
				response.setContentType("application/octet-stream");
				toClient.write(buffer);
				toClient.flush();
				toClient.close();
			} else {
				response.setContentType("text/html");
				try {
					response.getWriter().print("<html><body><h1>生成dxf文档失败，请刷新后重试！</h1></body></html>");
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		} catch (Exception e) {
			//log.error(e.getMessage(), e);
			e.printStackTrace();
			response.setContentType("text/html");
			try {
				response.getWriter().print("<html><body><h1>生成dxf文档失败，请刷新后重试！</h1></body></html>");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}






}
